package com.hainatong.shiphelper.module.handlejob.viewmodel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.api.ApiResult;
import com.hainatong.shiphelper.api.ApiService;
import com.hainatong.shiphelper.api.HttpResult;
import com.hainatong.shiphelper.api.VMObserver;
import com.hainatong.shiphelper.mainhome.entity.UploadImgBean;
import com.hainatong.shiphelper.mainhome.entity.WhereComBean;
import com.hainatong.shiphelper.module.handlejob.entity.ApplyHandleBean;
import com.hainatong.shiphelper.module.handlejob.entity.HandleInfoBean;
import com.hainatong.shiphelper.module.handlejob.entity.HandleParam;
import com.hainatong.shiphelper.module.holiday.entity.*;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.mvvmbase.base.BaseViewModel;
import com.hainatong.mvvmbase.base.LiveResult;
import com.hainatong.mvvmbase.base.PageLiveResult;
import com.hainatong.mvvmbase.http.RxSchedulersUtils;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class HandleJobViewModel extends BaseViewModel
{

    private int page;

    private boolean isRefresh = false;

    private boolean isHasNextPage = false;

    private String keyWord;

    private String userUuid;

    public HandleJobViewModel(@NonNull Application application)
    {
        super(application);
    }


    private MutableLiveData<LiveResult<Object>> handleTaskResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<Object>> getHandleTaskResult()
    {
        return handleTaskResult;
    }

    /**
     *  员工 提交 工作交接
     * @param
     */
    public void submitHandleJobTask(HandleParam param)
    {
        ApplyHandleBean applyParam = new ApplyHandleBean();
        applyParam.setMainData( param );
        ApiService.Builder.getChanBoServer()
                          .applyHandOverTask( applyParam )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<ApiResult<Object>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                  addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  getHandleTaskResult().postValue( new LiveResult<>( false ,errorMsg ) );
                              }

                              @Override
                              public void onSuccess(ApiResult<Object> result)
                              {
                                  //{
                                  //    "status": true,
                                  //    "code": "311",
                                  //    "message": "保存成功",
                                  //    "data": "{\"data\":{\"company\":\"H1\",\"company_id\":\"84\",\"Creator\":\"超级管理员\",\"CreateID\":\"ae\",
                                  // \"enddate\":\"2021-04-07\",\"port\":\"Aboshi\",\"port_id\":\"b26c428e-863b-11eb-b45c-5254006b78b4\",\"remark\":\"刺\",
                                  // \"ship_id\":\"53\",\"ship_name\":\"MT“ORESTINA”\",\"startdate\":\"2021-04-06\",\"status\":\"1\",\"total\":3,
                                  // \"user_id\":\"74d48e19-3e7c-4a00-ab82-2f3c5187d370\",\"username\":\"test2\",\"vactiontype\":\"临时休假（探亲）\",
                                  // \"vactiontype_id\":\"aa\",\"uuid\":\"fda\",\"CreateDate\":\"2021-04-08 17:02:59\"}}"
                                  //}
                                  if( result.getCode().equals("311")  )
                                  {
                                      getHandleTaskResult().postValue( new LiveResult<>( true ,result.getData() ) );
                                  }
                                  else
                                  {
                                      getHandleTaskResult().postValue( new LiveResult<>( false ,result.getMessage() ) );
                                  }
                              }
                          });

    }

    private MutableLiveData<LiveResult<List<DictFunBean>>> handleTypeResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<List<DictFunBean>>> getHandleTypeResult()
    {
        return handleTypeResult;
    }

    /**
     *  查询 工作交接 类型列表
     */
    public void queryHandOverTypeList()
    {
        //{"wheres":"[{\"name\":\"dict_type\",\"value\":\"Duty type\"},{\"name\":\"dict_level\",\"value\":\"1\"}]","rows":"50","page":"1"}
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE, "1");
        param.put( Constants.Key.ROWS, "100");
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "dict_type", "Duty type" ) );
        whereList.add( new WhereComBean( "dict_level", "1" ) );
        param.put( "wheres", GsonUtil.obj2json( whereList ));

        ApiService.Builder.getChanBoServer()
                          .getDictListByParam(param)
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<HttpResult<List<DictFunBean>>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                 addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  getHandleTypeResult().postValue( new LiveResult<>( false ,errorMsg ) );
                              }

                              @Override
                              public void onSuccess(HttpResult<List<DictFunBean>> result)
                              {
                                  if( result.isOk() )
                                  {
                                      getHandleTypeResult().postValue( new LiveResult<>( true ,result.getRows() ) );
                                  }
                                  else
                                  {
                                      getHandleTypeResult().postValue( new LiveResult<>( false ,result.getMsg() ) );
                                  }
                              }
                          });
    }






    private MutableLiveData<PageLiveResult<List<HandleInfoBean>>>  handleList = new MutableLiveData<>();

    public MutableLiveData<PageLiveResult<List<HandleInfoBean>>> getHandleList()
    {
        return handleList;
    }

    /**
     *  根据 提交人 查询
     * @param mPage
     * @param userId
     */
    private void  getUserHandleTaskList(int mPage, String userId)
    {
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE,  String.valueOf( mPage ) );
        param.put( Constants.Key.ROWS, ""+Constants.DEF_PAGE_SIZE);
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "CreateID", userId ) );
        //whereList.add( new WhereComBean( "dict_level", "1" ) );
        param.put( "wheres", GsonUtil.obj2json( whereList ));
        ApiService.Builder.getChanBoServer()
                .getUserHandOverList( param )
                .compose( RxSchedulersUtils.Obs_io_main() )
                .subscribe(new VMObserver<HttpResult<List<HandleInfoBean>>>()
                {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        PageLiveResult<List<HandleInfoBean>> errorResult = new PageLiveResult<>();
                        errorResult.setSuccess(false);
                        errorResult.setRefresh(isRefresh);
                        errorResult.setMsg(errorMsg);
                        if( !isRefresh )
                        {
                            errorResult.setLoadMoreEmpty(true);
                        }
                        getHandleList().postValue( errorResult );
                    }

                    @Override
                    public void onSuccess(HttpResult<List<HandleInfoBean>> result)
                    {
                        if( result.isOk() )
                        {
                            PageLiveResult<List<HandleInfoBean>> listResult = new PageLiveResult<>();
                            listResult.setSuccess(true);
                            listResult.setRefresh(isRefresh);
                            if( result.getRows() != null && !result.getRows().isEmpty() )
                            {
                                listResult.setData( result.getRows() );
                                if( result.getRows().size() < Constants.DEF_PAGE_SIZE )
                                {
                                    isHasNextPage = false;
                                }
                                else
                                {
                                    isHasNextPage = true;
                                    page = page + 1;
                                }
                            }
                            getHandleList().postValue(listResult);
                        }
                        else
                        {
                            PageLiveResult<List<HandleInfoBean>> failResult = new PageLiveResult<>();
                            failResult.setSuccess(false);
                            failResult.setRefresh(isRefresh);
                            failResult.setMsg(result.getMsg());
                            if( !isRefresh )
                            {
                                failResult.setLoadMoreEmpty(true);
                            }
                            getHandleList().postValue(failResult);
                        }
                    }
                });
    }

    /**
     *  查 交接 记录
     * @param userId
     */
    public void queryHandleHistoryByUser( String userId )
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        this.userUuid = userId;
        getUserHandleTaskList(this.page , this.userUuid );
    }

    public void tryRefreshHandle()
    {
        queryHandleHistoryByUser(this.userUuid);
    }

    public void loadMoreHandle()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            getUserHandleTaskList(this.page,this.userUuid);
        }
        else
        {
            PageLiveResult<List<HandleInfoBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getHandleList().postValue(emptyResult);
        }
    }






    private MutableLiveData<LiveResult<List<AuditProcessBean>>>  auditList = new MutableLiveData<>();

    public MutableLiveData<LiveResult<List<AuditProcessBean>>> getAuditList()
    {
        return auditList;
    }

    /**
     *  查询 休假 审批流程
     */
    public void getAuditProcessByVacId(String vacId)
    {

        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE,  "1" );
        param.put( Constants.Key.ROWS, "100");
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "audit_table", "sys_user_vacation" ) );
        whereList.add( new WhereComBean( "audit_tableid", vacId) );
        param.put( "wheres", GsonUtil.obj2json( whereList ));
        ApiService.Builder.getChanBoServer()
                          .getAuditProcessByParam( param )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<HttpResult<List<AuditProcessBean>>>()
               {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        getAuditList().postValue( new LiveResult<>( false ,errorMsg ) );
                    }

                    @Override
                    public void onSuccess(HttpResult<List<AuditProcessBean>> result)
                    {
                        if( result.isOk() )
                        {
                            getAuditList().postValue( new LiveResult<>( true ,result.getRows() ) );
                        }
                        else
                        {
                            getAuditList().postValue( new LiveResult<>( false ,result.getMsg() ) );
                        }
                    }
                });
    }





    private MutableLiveData<LiveResult<UploadImgBean>> upImgResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<UploadImgBean>> getUpImgResult()
    {
        return upImgResult;
    }

    /**
     *  上传 单张 图片
     * @param imgFile
     */
    public void upLoadImg(File imgFile)
    {

        RequestBody imgBody = RequestBody.create(MediaType.parse("image/*"), imgFile);
        MultipartBody.Part  body = MultipartBody.Part.createFormData( "file",imgFile.getName() , imgBody );

        ApiService.Builder.getChanBoServer()
                .uploadImgSingle(body)
                .compose(RxSchedulersUtils.Obs_io_main())
                .subscribe(new VMObserver<ApiResult<UploadImgBean>>()
                {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        getUpImgResult().postValue( new LiveResult<>( false ,errorMsg ) );
                    }

                    @Override
                    public void onSuccess(ApiResult<UploadImgBean> result)
                    {
                        if( result.isOk() )
                        {
                            getUpImgResult().postValue( new LiveResult<>( true , result.getData() ) );
                        }
                        else
                        {
                            getUpImgResult().postValue( new LiveResult<>( false , result.getMessage() ) );
                        }
                    }
                });
    }



}
